<template>
    <el-dialog draggable v-model="dialog.show" width="1140px" top="50px" :before-close="handleClose" class="custom-dialog">
      <template #header> {{ props.editData.id ? '修改' : '新增' }}供应商 </template>
      <div class="custom-dialog-box">
        <el-form :model="forms" inline ref="registerRef" :rules="rules" label-width="100">
          <el-form-item label="供应商编号" prop="providerSerialNo">
            <el-input v-model="forms.providerSerialNo" placeholder="供应商编号" clearable class="width-220"></el-input>
          </el-form-item>
          <el-form-item label="供应商名称" prop="providerName">
            <el-input v-model="forms.providerName" placeholder="供应商名称" clearable class="width-220"></el-input>
          </el-form-item>
          <el-form-item label="供应商归属" prop="belongType">
            <el-radio-group v-model="forms.belongType">
              <el-radio-button :label="item.value" v-for="item in custTypeData" :key="item">
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="省份" prop="provinces">
            <el-cascader v-model="forms.provinces" :options="china" :props="dialog.props" class="width-220" />
          </el-form-item>
          <el-form-item label="具体地址" prop="address">
            <el-input v-model="forms.address" placeholder="具体地址" clearable class="width-220"></el-input>
          </el-form-item>
          <el-form-item label="供应商等级" prop="levelType">
            <el-select v-model="forms.levelType" placeholder="供应商等级" clearable>
              <el-option v-for="item in custLevelType" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人" prop="officeId">
            <z-select v-model="forms.officeId" :options="dialog.officeOptions" placeholder="负责人" clearable class="width-220"></z-select>
          </el-form-item>
          <div class="w-100 dis-flex flex-center">
            <el-form-item label="备注" prop="note" class="flex-1 flex-y-center">
              <el-input v-model="forms.note" type="textarea" placeholder="备注" clearable class="w-100"></el-input>
            </el-form-item>
          </div>
        </el-form>
        <div class="provider">
          <el-alert title="联系人信息" type="success" center :closable="false" class="mb-10" />
          <z-button icon="add" type="success" size="small" title="添加联系人" circle class="provider-button" @click="onprovider"></z-button>
        </div>
        <el-table :data="forms.providerContacts" border stripe class="mb-20">
          <el-table-column prop="contactName" label="名称">
            <template #default="scope">
              <el-input v-model="scope.row.contactName" placeholder="请输入名称" clearable></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="contactPhone" label="联系方式">
            <template #default="scope">
              <el-input v-model="scope.row.contactPhone" placeholder="请输入联系方式" clearable></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="contactNote" label="备注">
            <template #default="scope">
              <el-input v-model="scope.row.contactNote" placeholder="请输入备注" clearable></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="isDefault" label="默认负责人">
            <template #default="scope">
              <el-switch
                v-model="scope.row.isDefault"
                :active-value="true"
                :inactive-value="false"
                active-text="启用"
                inactive-text="禁用"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="onStatusChange(scope.$index)"
              >
              </el-switch>
            </template>
          </el-table-column>
  
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <z-button icon="delete" type="danger" size="small" circle title="删除" @click="onDel(scope.$index)" v-if="purview(4)"></z-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <template #footer>
        <span class="dialog-footer">
          <z-button type="" @click="handleClose" icon="close">取消</z-button>
          <z-button icon="check" @click="onCheck" :loading="dialog.loading"> 确认 </z-button>
        </span>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { get, post } from '@/api/index';
  import { china, CodeToText } from '@/config/china';
  import { custTypeData, custLevelType } from '@/config/data';
  import { inject } from 'vue';
  let $message = inject('$message');
  let { purview } = inject('$global');
  let emit = defineEmits(['update:modelValue', 'onSave']);
  let store = useStore();
  let props = defineProps({
    modelValue: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  });
  let registerRef = ref();
  let dialog = reactive({
    show: false,
    loading: false,
    props: {
      expandTrigger: 'hover'
    },
    officeOptions: []
  });
  let formsInit = () => {
    return reactive({
      id: 0,
      providerSerialNo: '',
      providerName: '',
      belongType: 1,
      provinces: [],
      provincesName: '',
      address: '',
      levelType: undefined,
      officeId: undefined,
      note: '',
      providerCreditCode: '',
      ticketTitle: '',
      ticketProvinces: '',
      ticketProvincesName: '',
      ticketAddress: '',
      ticketTaxSerialNo: '',
      ticketBank: '',
      ticketBankAccount: '',
      ticketPhone: '',
      ticketNote: '',
      providerContacts: [],
      customSpecValueDic: {}
    });
  };
  let forms = formsInit();
  let rules = {
    providerSerialNo: [{ required: true, trigger: 'change', message: '编号不能为空!' }],
    providerName: [{ required: true, trigger: 'change', message: '名称不能为空!' }],
    officeId: [{ required: true, trigger: 'change', message: '负责人不能为空!' }]
  };
  watch(
    () => props.modelValue,
    async val => {
      dialog.show = val;
      if (!val) return;
      let formData = formsInit();
      Object.keys(formData).map(r => {
        forms[r] = props.editData[r] != undefined ? props.editData[r] : formData[r];
      });
      if (props.editData.id) {
        getDetail();
        return;
      }
    },
    {
      immediate: true
    }
  );
  // 关闭
  const handleClose = () => {
    registerRef.value.resetFields();
    emit('update:modelValue', false);
  };
  // 确认
  const onCheck = async () => {
    if (!registerRef.value) return;
    registerRef.value.validate(async val => {
      if (!val) return;
      try {
        dialog.loading = true;
        forms.provincesName = forms.provinces.map(r => CodeToText[r]).join('-');
        forms.provinces = forms.provinces.length && forms.provinces.join(',');
        await post('provider/AddOrUpdate', forms);
        $message.success(`${props.editData.id ? '修改' : '新增'}成功`);
        dialog.loading = false;
        emit('onSave');
        registerRef.value.resetFields();
      } catch (error) {
        console.log('provider/AddOrUpdate 错误', error);
        dialog.loading = false;
      }
    });
  };
  // 详情接口
  const getDetail = async () => {
    let { result } = await get('provider/GetModel', { id: props.editData.id });
    const formData = formsInit();
    Object.keys(formData).map(r => {
      forms[r] = result[r] != undefined ? result[r] : formData[r];
      if (r === 'provinces') forms[r] = result[r].split(',');
    });
    dialog.officeOptions = [{ label: result.officeName, value: result.officeId }];
  };
  // 添加联系人
  const onprovider = () => {
    forms.providerContacts.push({
      contactName: '',
      contactPhone: '',
      contactNote: '',
      isDefault: forms.providerContacts.length ? false : true
    });
  };
  
  const onStatusChange = index => {
    let type = forms.providerContacts[index].isDefault;
    forms.providerContacts.map((r, i) => {
      r.isDefault = index === i ? type : false;
    });
  };
  
  // 删除联系人
  const onDel = index => {
    forms.providerContacts.splice(index, 1);
  };
  </script>
  
  <style lang="scss" scoped>
  .provider {
    position: relative;
    :deep(.provider-button) {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  </style>
  